package com.itstudy.rpc;

import com.itstudy.common.JSONSerializer;
import com.itstudy.common.RpcDecoder;
import com.itstudy.common.RpcRequest;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @ClassName: RpcRegistry
 * @Auther: Jerry
 * @Date: 2020/8/18 0:04
 * @Desctiption: TODO
 * @Version: 1.0
 */
public class RpcRegistry {

    private int port;

    public RpcRegistry(int port) {
        this.port = port;
    }

    public void start(){
        try {
            //1.创建两个线程池对象
            NioEventLoopGroup bossGroup = new NioEventLoopGroup();
            NioEventLoopGroup workGroup = new NioEventLoopGroup();
            //2.创建服务端的启动引导对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //3.配置启动引导对象
            serverBootstrap.group(bossGroup, workGroup)
                    //设置通道为NIO
                    .channel(NioServerSocketChannel.class)
                    //创建监听channel
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                    //获取管道对象
                    ChannelPipeline pipeline = nioSocketChannel.pipeline();
                    //给管道对象pipeLine 设置编码
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                    pipeline.addLast(new RpcRegistryHandler());
                }
            });
            //4.绑定端口
            serverBootstrap.bind(port).sync();
            System.out.println("RPC Registry start listen at:" + port);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new RpcRegistry(8999).start();
    }
}
